<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/11/2
 * Time: 08:38
 */

namespace Common\Api;


use Api\Service\OAuth2ClientService;
use Api\Vendor\BoyeUtils\BoyeUtils;

/**
 * 以接口方式调用博也PHP接口.
 * Class BoyeServiceApi
 * @package Common\Api
 */
class BoyeServiceApi {

    private $apiUrl ;//接口地址，根地址
    private $client_id;
    private $client_secret;

    function __construct(){
        $this->apiUrl = C('API_URL').'/';
        $this->client_id = CLIENT_ID;
        $this->client_secret = CLIENT_SECRET;
    }

    /**
     * @param $url Orders/add 接口方法
     * @param $data
     * @param bool $is_debug
     * @return array
     * @throws \Exception
     */
    public function callRemote($url, $data,$is_debug=false){

        $type = $data['type'];
        $api_ver = $data['api_ver'];
        $notify_id = $data['notify_id'];
        $alg = $data['alg'];

        if(empty($this->client_id)){
            return array('status' => false, 'info' => "缺少client_id参数!");
        }
        unset($data['client_id']);
        if(empty($type)){
            return array('status' => false, 'info' => "缺少type参数!");
        }
        unset($data['type']);
        if(empty($api_ver)){
            return array('status' => false, 'info' => "缺少api_ver参数!");
        }
        unset($data['api_ver']);
        if(empty($notify_id)){
            return array('status' => false, 'info' => "缺少notify_id参数!");
        }
        unset($data['notify_id']);
        if(empty($alg)){
            return array('status' => false, 'info' => "缺少alg参数!");
        }
        unset($data['alg']);

        $encrypt_data = BoyeUtils::encrypt($data);

        $param = array(
            'client_id'=>$this->client_id,
            'api_ver'=>$api_ver,
            'notify_id'=>$notify_id,
            'time'=>strval(time()),
            'data'=>$encrypt_data,
            'type'=>$type,
            'alg'=>$alg,
        );

        $param['sign'] = BoyeUtils::sign($param);

        $param['access_token'] = $this->getAccessToken();

        $result = $this->curlPost($url,$param);
        if($is_debug){
            dump("加密后的数据");
            dump($result);
        }
        if($result['status']){

            $info = $result['info'];
            if(isset($info['data']) && isset($info['sign'])){

                $decrypt_data = BoyeUtils::decrypt($info['data']);

                if(!BoyeUtils::verify_sign($info['sign'],$info)){
                    $result = array('status'=>false,'info'=>'返回数据签名验证失败!');
                }

                if($decrypt_data['code'] != 0){
                    $result = array('status'=>false,'info'=>$decrypt_data['data']);
                }else{
                    $result = array('status'=>true,'info'=>$decrypt_data['data'],'notify_id'=>$decrypt_data['notify_id']);
                }

            }else{
                $result = array('status'=>false,'info'=>$info);
            }

        }

        //TODO: 对data加密
        return $result;
    }

    /**
     * 取得accessToken
     * @return mixed
     */
    public function getAccessToken(){
        return CLIENT_ID;
        $access_token = S('boye_access_token');

        if(empty($access_token)){
            $config = array(
                'client_id'=>$this->client_id,
                'client_secret'=>$this->client_secret,
                'site_url'=>C("SITE_URL"),
            );

            $client = new OAuth2ClientService($config);
            $access_token = $client->getAccessToken();
            $access_token = $access_token['info'];

            S('boye_access_token',$access_token,60*18);
        }
        return $access_token['access_token'];
    }


    /**
     *
     * @param $url Orders/add
     * @param $data  array
     * @return array
     */
    protected function curlPost($url, $data) {

        $url = $this->apiUrl.$url;
        $url = rtrim($url,"/");
        //对data进行加密
        $ch = curl_init();
        $header = array('Accept-Charset'=>"utf-8");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.64 Safari/537.36');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        $errorno = curl_errno($ch);

        if ($errorno) {
            return array('status' => false, 'info' => $errorno);
        } else {

            $js = json_decode($tmpInfo,true);
            if(is_null($js)){
                $js = "$tmpInfo";
            }
            return array('status' => true, 'info' => $js);
        }
    }

}